<?php
namespace App\Models;

class SmsLog extends BaseModel
{

    protected $table = 'sms_log';
    public $timestamps = false;

    const DEFAULT_CONNECT_SMS_TIME = 90;

    const DEFAULT_CONNECT_SMS_PHONE = 5;

    const DEFAULT_CONNECT_SMS_IP = 20;

    const DEFAULT_CONNECT_SMS_USED_TIME = 30;

    /**
     * 增加短信记录
     *
     * @param
     * @return int
     */
    public function addSms($data)
    {
        return $this->_add($data);
    }

    /**
     * 查询单条记录
     *
     * @param
     * @return array
     */
    public function getSmsInfo($where)
    {
        if (empty($where)) {
            return false;
        }
        return $this->_getOne($where);
    }

    /**
     * 查询记录
     *
     * @param
     * @return array
     */
    public function getSmsList($where = array())
    {
        return $this->_getList($where, '*', ['id' => 'desc']);
    }

    /**
     * 取得记录数量
     *
     * @param
     * @return int
     */
    public function getSmsCount($where)
    {
        return $this->_count($where);
    }

    /**
     * 获取手机短信验证码
     */
    public function getSmsCaptcha($mobile, $type, $mid)
    {
        $ajaxData = ['status' => false, 'msg' => '验证码或手机号码不正确','sms_time'=>self::DEFAULT_CONNECT_SMS_TIME];
        if (strlen($mobile) == 11) {
            $ajaxData = $this->sendCaptcha($mobile, $type, $mid);
        }
        return $ajaxData;
    }

    /**
     * 验证验证码
     * @param string $phone
     * @param string $captcha
     * @param string $log_type
     * @return array
     */
    public function checkSmsCaptcha($mobile,$captcha,$type)
    {
        $state = 1;
        $msg = '手机验证码验证成功';
        $where['log_phone'] = $mobile;
        $where['log_captcha'] = $captcha;
        $where['log_type'] = $type;
        $res = $this->getSmsInfo($where);
        if (empty($res) || ($res['add_time'] < time() - 1800)) {//半小时内进行验证为有效
            $state = 0;
            $msg = '验证码错误或已过期，重新输入';
        }
        $ajaxData = ['status' => $state, 'msg' => $msg];
        return $ajaxData;
    }


    /**
     * 发送手机动态码
     * @param string $phone
     * @param string $logType 短信类型:1用户账号移交,2送水工账号移交
     * @return array
     */
    public function sendCaptcha($phone, $logType, $uid = 0)
    {
        $state = true;
        $msg = '手机动态码发送成功';
        $sms_log = $this->ipCaptcha($logType);
        $now = time();
        if (!empty($sms_log) && ($sms_log['add_time'] > $now - self::DEFAULT_CONNECT_SMS_TIME)) {//同一IP[n]秒内只能发一条短信
            $state = false;
            $msg = '同一IP地址' . self::DEFAULT_CONNECT_SMS_TIME . '秒内，请勿多次获取验证码！';
        }
        $where['log_phone'] = $phone;
        $where['log_type'] = $logType;
        $sms_log = $this->getSmsInfo($where);
        if ($state && !empty($sms_log) && ($sms_log['add_time'] > $now - self::DEFAULT_CONNECT_SMS_TIME)) {//同一手机号IP[n]秒内只能发一条短信
            $state = false;
            $msg = '同一手机号' . self::DEFAULT_CONNECT_SMS_TIME . '秒内，请勿多次获取验证码！';
        }
        $time24 = $now - 60 * 60 * 24;
        $where = [];
        $where['log_phone'] = $phone;
        $where['add_time'] = ['<', $time24];
        $num = $this->getSmsCount($where);
        if ($state && $num >= self::DEFAULT_CONNECT_SMS_PHONE) {//同一手机号24小时内只能发5条短信
            $state = false;
            $msg = '同一手机号24小时内，请勿多次获取验证码！';
        }
        $where = [];
        $where['log_ip'] = request()->ip();
        $where['add_time'] = ['<', $time24];
        $num = $this->getSmsCount($where);
        if ($state && $num >= self::DEFAULT_CONNECT_SMS_IP) {//同一IP24小时内只能发20条短信
            $state = false;
            $msg = '同一IP24小时内，请勿多次获取验证码！';
        }
        if ($state == true) {
            $logData = [];
            $captcha = rand(1000, 9999);
            $logMsg = '【趣订水】';
            //短信类型:1预约成功,2绑定就诊人,3改签,4充值成功（废弃 by yuFan）
            //短信类型:1,账号移交,2,个人资料,3,开店注册
            switch ($logType) {
                case 1:
                    //验证码为#code#，您正在进行账号移交，请于#time#分钟内正确输入，请确认是本人操作。
                    $logMsg = ' 验证码为' . $captcha . '，您正在进行账号移交，请于' . self::DEFAULT_CONNECT_SMS_USED_TIME . '分钟内正确输入，请确认是本人操作。';
                    break;
                case 2:
                    //您的验证码是#code#。如非本人操作，请忽略本短信
                    $logMsg = ' 您的验证码是' . $captcha . '。如非本人操作，请忽略本短信';
                    break;
                case 3:
                    $logMsg = ' 您的验证码是' . $captcha . '。如非本人操作，请忽略本短信';
                    break;
                default:
                    $state = false;
                    $msg = '参数错误';
                    break;
            }
            if ($state == true) {
                $logData['user_id'] = $uid ? $uid : request('mid', 0);
//                $smsTmpl = new SmsTmpl();
//                $tmpl = $smsTmpl->getSmsTmplById($logType);
                $apikey = 'a3f933e0ffd6392339ab816a058a6521';
                $result = $this->sendSMS($apikey, $logMsg, $phone);
                if ($result) {
                    $logData['log_phone'] = $phone;
                    $logData['log_captcha'] = $captcha;
                    $logData['log_ip'] = request()->ip();
                    $logData['log_msg'] = json_encode($logMsg);
                    $logData['log_type'] = $logType;
                    $logData['add_time'] = $now;
                    $this->addSms($logData);
                } else {
                    $state = false;
                    $msg = '手机短信发送失败';
                }
            }
        }
        $state_data = [
            'status' => $state,
            'sms_time' => self::DEFAULT_CONNECT_SMS_TIME,
            'msg' => $msg
        ];
        return $state_data;
    }

    /**
     * 按IP查询手机验证码
     * @param string $logType
     * @return array
     */
    public function ipCaptcha($logType = '')
    {
        $where = array();
        $where['log_ip'] = request()->ip();
        $logType = intval($logType);
        if ($logType > 0) {
            $where['log_type'] = $logType;//短信类型:1预约成功,2绑定就诊人,3改签,4充值成功
        }
        $res = $this->getSmsInfo($where);
        return $res;
    }


    public function sendSms($apikey, $content, $mobile)
    {

        $yunpian = new \Yunpian\Sdk\YunpianClient();
//初始化client,apikey作为所有请求的默认值
        $clnt = $yunpian->create($apikey);
        $param = [$yunpian::MOBILE => $mobile, $yunpian::TEXT =>$content];
//        tolog($param);
        $r = $clnt->sms()->single_send($param);
//var_dump($r);
//        tolog($r);
        if (!$r->isSucc()) {
            return false;
        }
        return true;
    }

//    public function sendSms($apikey, $content, $mobile)
//    {
//        $path = '/v1/sms/send.json';
//        $host = 'yunpian.com';
//        $client = new \App\Support\HttpClient($host);
//        $client->setDebug(false);
//        $data = [
//            'apikey' => $apikey,
//            'text' => $content,
//            'mobile' => $mobile,
//            'tpl_id' => $tpl_id,
//            'tpl_value' => $encoded_tpl_value
//        ];
//        if (!$client->post($path, $data)) {
//            $this->error = $client->errormsg;
//            return false;
//        }
//        $result = json_decode($client->getContent());
//        if ($result->code != 0) {
//            $this->error = $result->msg;
//            return false;
//        }
//        return true;
//    }

    public function clear()
    {
        //超过24小时
        $time = time() - 86400;
        $where['add_time'] = ['<',$time];
        $this->_del($where);
    }

}
